//
//  SSDKEncryptUtil.m
//  OpenSDK
//
//  Created by wyht－ios－dev on 15/10/7.
//  Copyright © 2015年 WYHT. All rights reserved.
//

#import "OpenSDK_EncryptUtil.h"

#import "OpenSDK_DataKeys.h"

#import "OpenSDK_MD5.h"

#import "OpenSDK_JsonUtil.h"

//#import "OpenSDK_RSA.h"
#import "OpenSDK_Base64.h"
#import "OpenSDK_DataManager.h"
#import "OPKRSAObjC.h"

@implementation OpenSDK_EncryptUtil

//字节数组分隔长度
static int rsaLength=100;


+ (NSString *) generateSignWithDictionary:(NSMutableDictionary *)dictionary
                               useSignKey:(NSString *)key
                             useSignValue:(NSString *)value
{
    NSString *encStr = [self generateNormalizedStringWithDictionary:dictionary
                                                        withoutKey:OpenSDK_SIGN];
    encStr = [[value stringByAppendingString:encStr]
              stringByAppendingString:value];
    return [OpenSDK_MD5 md5:encStr];
}

+ (NSString *) generateNormalizedStringWithDictionary:(NSMutableDictionary *)dictionary
                                           withoutKey:(NSString *)key {
    NSArray *keyArray = [dictionary allKeys];
    NSArray *sortedArray = [keyArray sortedArrayUsingSelector:@selector(compare:)];
    
    NSString *sb = [[NSString alloc] init];
    for (NSString* k in sortedArray) {
        if ([k isEqualToString:key]) {
            continue;
        }
        NSString *value = [dictionary valueForKey:k];
        if (!value) {
            value = @"";
        }
        
        value = [[value dataUsingEncoding:NSUTF8StringEncoding] base64Encoding];
        sb = [[[sb stringByAppendingString: k]
               stringByAppendingString: @"="]
              stringByAppendingString:value];
    }
    return sb;
    
}

+ (BOOL) checkSignWithDictionary:(NSMutableDictionary *)dictionary
                      useSignKey:(NSString *)key
                      useSignValue:(NSString *)signValue {
    NSString *sign = [dictionary valueForKey:OpenSDK_SIGN];
    if (!sign) {
        return NO;
    }
    
    NSString *checkSign = [OpenSDK_EncryptUtil generateSignWithDictionary:dictionary useSignKey:key useSignValue:signValue];
    if ([checkSign isEqualToString:sign]) {
        return YES;
    }
    return NO;
}

//通过公钥签名数据,以100字节分组
//+(NSString *) generateRSAResultByData:(NSMutableDictionary *)data
//{
//    NSString *pubKey=[[OpenSDK_DataManager getInstance] appPubKey];
//    NSString *pubKeyL=[OpenSDK_EncryptUtil generateRSAPublicKeyStr:[NSMutableString stringWithString:pubKey]];
//    SSCrypto *crpty = [[SSCrypto alloc] initWithPublicKey:[pubKeyL dataUsingEncoding:NSUTF8StringEncoding]];
//
//    NSString *dataStr=[OpenSDK_JsonUtil toJsonWithObject:data];
//    NSData *dataNSTotal=[dataStr dataUsingEncoding:NSUTF8StringEncoding];
//    //NSData *dataNSTotal=[[NSData alloc] initWithBytes:[dataStr UTF8String] length:[dataStr length]];
//    Byte *testByte = (Byte *)[dataNSTotal bytes];
//    int max=[dataNSTotal length];
//    //服务器加密分割为100字节
//    int c=max%rsaLength==0?max/rsaLength:(max/rsaLength+1);
//    //临时数组的长度
//    int tmpByteLength=0;
//    //最终的字符串
//    NSMutableData *resultData = [[NSMutableData alloc] init];
//    for(int i=1;i<=c;i++)
//    {
//        if((max-i*rsaLength)>=0)
//            tmpByteLength=rsaLength;
//        else
//            tmpByteLength=rsaLength-(i*rsaLength-max);
//
//        Byte byte[tmpByteLength];
//        memcpy(&byte, &testByte[(i-1)*rsaLength], tmpByteLength);
//        NSData *tmpData = [[NSData alloc] initWithBytes:byte length:tmpByteLength];
//        [crpty setClearTextWithData:tmpData];
//
//        [resultData appendData:[crpty encrypt]];
//    }
//
//    NSString *resultStr=[MF_Base64Codec base64StringFromData:resultData];
//
//    return resultStr;
//}

+(NSString *) generateRSAResultByData:(NSMutableDictionary *)data
{
    NSString *pubKey=[[OpenSDK_DataManager getInstance] appPubKey];
    NSString *dataStr=[OpenSDK_JsonUtil toJsonWithObject:data];
    NSString *resultStr = [OPKRSAObjC encrypt:dataStr PublicKey:pubKey];
    return resultStr;
}

+(NSString *) generateMD5ResultByData:(NSMutableDictionary *) data{
    NSArray *keys = [data.allKeys sortedArrayUsingSelector:@selector(compare:)];
    NSString *str = @"";
    for (NSString *key in keys) {
        str = [str stringByAppendingFormat:@"%@=%@",key,[[[data objectForKey:key] dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0]];
    }
    NSString *secretKey = [OpenSDK_DataManager getInstance].secret_key;
    return [OpenSDK_MD5 md5:[NSString stringWithFormat:@"%@%@%@",secretKey,str,secretKey]];
}

//根据java的公钥生成key
//+(NSString *) generateRSAPublicKeyStr:(NSMutableString *) strFromJava
//{
//    NSString *headStr=@"-----BEGIN PUBLIC KEY-----\r\n";
//    int max=strFromJava.length;
//    //文件要求必须是64位开始计算
//    int c=max%64==0?max/64:(max/64+1);
//    int curLocation=0;
//    for (int i=1; i<=c; i++) {
//        curLocation=64*i+2*(i-1);
//        if(curLocation<=(max+2*(i-1)))
//            [strFromJava insertString:@"\r\n"  atIndex:curLocation];
//        else
//            [strFromJava insertString:@"\r\n" atIndex:strFromJava.length];
//    }
//    strFromJava=[headStr stringByAppendingString:strFromJava];
//    NSString *endStr=@"-----END PUBLIC KEY-----\r\n";
//    strFromJava=[strFromJava stringByAppendingString:endStr];
//    
//    return strFromJava;
//}

@end
